/**
 * @author harry
 * @date 2022/2/27/11:28
 */

package com.serviceOrchestration.controller;

import com.serviceOrchestration.annotation.RoleRestriction;
import com.serviceOrchestration.exception.LoginException;
import com.serviceOrchestration.pojo.ReturnData;
import com.serviceOrchestration.service.LoginService;
import com.serviceOrchestration.util.Role;
import com.serviceOrchestration.util.StatusCode;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户登录登出接口")
public class UserController {

    private final LoginService loginService;

    @Autowired
    public UserController(LoginService loginService) {
        this.loginService = loginService;
    }

    @ApiOperation(value = "用户登录", notes = "用户在客户端使用账号密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", type = "String", required = true, example = "18012345678"),
            @ApiImplicitParam(name = "password", type = "String", required = true, example = "123")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录成功", responseHeaders = {
                    @ResponseHeader(name = "Authorization", description = "Bearer TOKEN")
            }),
            @ApiResponse(code = 404, message = "未找到账号")
    })
    @PostMapping("/login")
    public ReturnData<?> login(@RequestBody Map<String, String> params, HttpServletResponse response) throws LoginException {
        String id = params.get("id");
        String password = params.get("password");
        Map<String, Object> ret = loginService.userLogin(id, password);
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.AUTHORIZATION);
        response.setHeader(HttpHeaders.AUTHORIZATION, (String) ret.get("token"));
        return ReturnData.ok(ret.get("user"));
    }

    @ApiOperation(value = "用户登出", notes = "客户端带token退出登录")
    @ApiImplicitParam(name = "token", dataType = "String", required = true)
    @RoleRestriction(Role.USR)
    @GetMapping("/logout")
    public ReturnData<?> logout(@RequestAttribute("token") String token) {
        if (loginService.logout(token)) {
            return ReturnData.ok();
        }
        return ReturnData.error(StatusCode.SERVER_ERROR);
    }
}
